package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static  final String UPDATE_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";

    @Autowired
    private SqlSessionFactory factory;

    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
        System.out.println("批量删除库存");//14735550211
        //测试的错误
//        HashMap<String, Object> param2 = new HashMap<>();
//        param2.put("id",14735550211L);
//        param2.put("num",1);
//        Long id = 14735550211L;
//        Integer num  = 2;
//        this.baseMapper.deductStock1(id,num);
        //使用mybatisplus的批处理
        try {
            executeBatch(sqlSession -> {
                //遍历sku
                for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                    //调用mapper中的方法
                    HashMap<String, Object> param = new HashMap<>();
                    param.put("id",entry.getKey());
                    param.put("num",entry.getValue());
                    System.out.println("id = " + entry.getKey());
                    System.out.println("num = " + entry.getValue());
                    //使用这种方法全路径来调用方法
                    sqlSession.update(UPDATE_STOCK_STATEMENT,param);
                }
                //刷新和提交
                sqlSession.flushStatements();
            });
        } catch (Exception e) {
            throw new LyException(400,"库存不足");
        }

//        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
//            Long skuId = entry.getKey();
//            Integer num = entry.getValue();
//            // 查询sku
//            Sku sku = getById(skuId);
//            //  判断库存是否充足
//            if (sku.getStock() < num) {
//                // 如果不足，抛出异常
//                throw new LyException(400, "库存不足！");
//            }
//
//            // 如果充足，扣减库存 update tb_sku set stock = stock - 1, sold = sold + 1  where id = 1
//            Map<String,Object> param = new HashMap<>();
//            param.put("id", skuId);
//            param.put("num", num);
//            getBaseMapper().deductStock(param);
//        }
    }
}